<?php
namespace app\pub\controller;
use think\Validate;
use think\Controller;

class Ueditor extends Controller
{
  private $sub_name = array('date', 'Y/m-d');
  private $savePath = 'images/';
  private $ueditorJson = "./public/static/ueditor/php/config.json";
  public function __construct()
  {
      parent::__construct();
      
      //header('Access-Control-Allow-Origin: http://www.baidu.com'); //设置http://www.baidu.com允许跨域访问
      //header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); //设置允许的跨域header
      
      date_default_timezone_set("Asia/Shanghai");
      
      $this->savePath = input('savepath','images').'/';
      
      error_reporting(E_ERROR | E_WARNING);
      
      header("Content-Type: text/html; charset=utf-8");
  }
  
  public function index(){
      
      $CONFIG2 = json_decode(
        preg_replace("/\/\*[\s\S]+?\*\//", "", 
          file_get_contents($this->ueditorJson)), true);
      //dd($CONFIG2);
  
      $action = $_GET['action'];
      //dd($action);
      switch ($action) {
          case 'config':
              $result =  json_encode($CONFIG2);
              break;
          /* 上传图片 */
          case 'uploadimage':
              $fieldName = $CONFIG2['imageFieldName'];
              $result = $this->upFile($fieldName);
              break;
          /* 上传涂鸦 */
          case 'uploadscrawl':
              $config = array(
                  "pathFormat" => $CONFIG2['scrawlPathFormat'],
                  "maxSize" => $CONFIG2['scrawlMaxSize'],
                  "allowFiles" => $CONFIG2['scrawlAllowFiles'],
                  "oriName" => "scrawl.png"
              );
              $fieldName = $CONFIG2['scrawlFieldName'];
              $base64 = "base64";
              $result = $this->upBase64($config,$fieldName);
              break;
          /* 上传视频 */
          case 'uploadvideo':
              $fieldName = $CONFIG2['videoFieldName'];
              $result = $this->upFile($fieldName);
              break;
          /* 上传文件 */
          case 'uploadfile':
              $fieldName = $CONFIG2['fileFieldName'];
              $result = $this->upFile($fieldName);
              break;
          /* 列出图片 */
          case 'listimage':
              $allowFiles = $CONFIG2['imageManagerAllowFiles'];
              $listSize = $CONFIG2['imageManagerListSize'];
              $path = $CONFIG2['imageManagerListPath'];
              $get =$_GET;
              $result =$this->fileList($allowFiles,$listSize,$get);
              break;
          /* 列出文件 */
          case 'listfile':
              $allowFiles = $CONFIG2['fileManagerAllowFiles'];
              $listSize = $CONFIG2['fileManagerListSize'];
              $path = $CONFIG2['fileManagerListPath'];
              $get = $_GET;
              $result = $this->fileList($allowFiles,$listSize,$get);
              break;
          /* 抓取远程文件 */
          case 'catchimage':
              $config = array(
                  "pathFormat" => $CONFIG2['catcherPathFormat'],
                  "maxSize" => $CONFIG2['catcherMaxSize'],
                  "allowFiles" => $CONFIG2['catcherAllowFiles'],
                  "oriName" => "remote.png"
              );
              $fieldName = $CONFIG2['catcherFieldName'];
              /* 抓取远程图片 */
              $list = array();
              isset($_POST[$fieldName]) ? $source = $_POST[$fieldName] : $source = $_GET[$fieldName];
              
              foreach($source as $imgUrl){
                  $info = json_decode($this->saveRemote($config,$imgUrl),true);
                  array_push($list, array(
                      "state" => $info["state"],
                      "url" => $info["url"],
                      "size" => $info["size"],
                      "title" => htmlspecialchars($info["title"]),
                      "original" => htmlspecialchars($info["original"]),
                      "source" => htmlspecialchars($imgUrl)
                  ));
              }
              $result = json_encode(array(
                  'state' => count($list) ? 'SUCCESS':'ERROR',
                  'list' => $list
              ));
              break;
          default:
              $result = json_encode(array(
                  'state' => '请求地址出错'
              ));
              break;
      }
      /* 输出结果 */
      if(isset($_GET["callback"])){
          if(preg_match("/^[\w_]+$/", $_GET["callback"])){
              echo htmlspecialchars($_GET["callback"]).'('.$result.')';
          }else{
              echo json_encode(array(
                  'state' => 'callback参数不合法'
              ));
          }
      }else{
          echo $result;
          
      }
      exit;
  }
  
  //上传文件
  private function upFile($fieldName){
      $file = I($fieldName);
      //dd($file);
      /* $result = $this->validate(
              ['file2' => $file],
              ['file2'=>'image','file2'=>'fileSize:40000000'],
              ['file2.image' => '上传文件必须为图片','file2.fileSize' => '上传文件过大']
      ); */
      
      
      if (true !== $result || empty($file)) {
          $state = "ERROR" . $result;
      }else{

        $qiNiu = I("qiniu", 0);

        if($qiNiu){
          $fileOut = $this->qiNiu($file);
          $data = array(
              'state' => 'SUCCESS',
              'url' => $fileOut, 
              'title' => $file->info['name'],
              'original' => $file->info['name'],
              'type' => '.' . $this->getExt($file->info['name']) ,
              'size' => $file->info['size'],
          );
          return json_encode($data);
          
        }else{
          // 移动到框架应用根目录/public/uploads/ 目录下
          $this->savePath = $this->savePath.date('Y').'/'.date('m-d').'/';
          // 使用自定义的文件保存规则
          //$info = $file->rule(function ($file) {
          //    return  md5(mt_rand());
          //  })->move('public/upload/'.$this->savePath);
          $filename = md5(mt_rand());
          copy($this->savePath . '/' . $fieldName );
        }

      }
      
      if($info){
          $data = array(
              'state' => 'SUCCESS',
              'url' => 'public/upload/'.$this->savePath.$info->getSaveName(),
              'title' => $info->getFilename(),
              'original' => $info->getFilename(),
              'type' => '.' . $info->getExtension(),
              'size' => $info->getSize(),
          );
          //图片加水印
          if($this->savePath=='Goods/'){
              $image = new \Think\Image();
              $water = tpCache('water');
              $imgresource = ".".$data['url'];
              $image->open($imgresource);
              if($water['is_mark']==1 && $image->width()>$water['mark_width'] && $image->height()>$water['mark_height']){
                  if($water['mark_type'] == 'text'){
                      $image->text($water['mark_txt'],'./hgzb.ttf',20,'#000000',9)->save($imgresource);
                  }else{
                      $image->water(".".$water['mark_img'],9,$water['mark_degree'])->save($imgresource);
                  }
              }
          }
      }else{
          $data = array('state' => $state.$info->getError());
      }
      return json_encode($data);
  }

/**
   * 七牛上传
   */
  public function qiNiu($file)
  {
    //$file = request()->file('file');

    $config = config('qiniu');
    $auth = new Auth($config['access_key'], $config['secret_key']);
    $token = $auth->uploadToken($config['bucket']); // 空间名
    $uploadMgr = new UploadManager();

    list($ret, $err) = $uploadMgr->putFile($token, $pic_name, $file->info['tmp_name']);
    if ($err !== null) {
        //return array("status"=>0, "info"=>$err);
        $this->error($err);
    } else {
      return $config['domain'] . "/" . $ret['key']; 
        //var_dump($ret);
        //echo '图片地址为：<a target="_blank" href="'.$config['domain'] .'/'.$ret['key'].'">'.$ret['key'].'</a>';
        /* return array("status"=>1, "info"=>$config['domain'] . "/" . $ret['key'], 
            "data"=>array(
                "name" => $pic_name,
                "original" =>$name,
                "ext" => $ext,
                "size" => $size,
            )
        ); */
    }
  }
  function getExt($file){
      return end(explode(".",$file));
  }
  //列出图片
  private function fileList($allowFiles,$listSize,$get){
      $dirname = './public/upload/';
      $allowFiles = substr(str_replace(".","|",join("",$allowFiles)),1);
      /* 获取参数 */
      $size = isset($get['size']) ? htmlspecialchars($get['size']) : $listSize;
      $start = isset($get['start']) ? htmlspecialchars($get['start']) : 0;
      $end = $start + $size;
      /* 获取文件列表 */
      $path = $dirname;
      $files = $this->getFiles($path,$allowFiles);
      if(!count($files)){
          return json_encode(array(
              "state" => "no match file",
              "list" => array(),
              "start" => $start,
              "total" => count($files)
          ));
      }
      /* 获取指定范围的列表 */
      $len = count($files);
      for($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--){
          $list[] = $files[$i];
      }
      /* 返回数据 */
      $result = json_encode(array(
          "state" => "SUCCESS",
          "list" => $list,
          "start" => $start,
          "total" => count($files)
      ));
      return $result;
  }
      /*
    * 遍历获取目录下的指定类型的文件
    * @param $path
    * @param array $files
    * @return array
  */
  private function getFiles($path,$allowFiles,&$files = array()){
      if(!is_dir($path)) return null;
      if(substr($path,strlen($path)-1) != '/') $path .= '/';
      $handle = opendir($path);
          
      while(false !== ($file = readdir($handle))){
          if($file != '.' && $file != '..'){
              $path2 = $path.$file;
              if(is_dir($path2)){
                  $this->getFiles($path2,$allowFiles,$files);
              }else{
                  if(preg_match("/\.(".$allowFiles.")$/i",$file)){
                      $files[] = array(
                          'url' => substr($path2,1),
                          'mtime' => filemtime($path2)
                      );
                  }
              }
          }
      }        
      return $files;
  }
}